version 16.1
clear all
cd "MYPATH\derived\build_income_tiles"
adopath + ../../ado/

cap log close
log using "build.log", replace

preliminaries
foreach PATH in RESULTS TEMP {
	if "`PATH'" != "TEMP" cap mkdir "${`PATH'}\derived\build_income_tiles"
    if "`PATH'" != "TEMP" cap mkdir "${`PATH'}\derived\build_income_tiles\figures"
	if "`PATH'" == "TEMP" cap mkdir "${`PATH'}\derived\build_income_tiles"
}

graph set window fontface default
graph set ps fontface default
graph set window fontfacemono "Consolas"
graph set ps fontfacemono "Consolas"


program main 
	* Income tiles relative to mothers who give birth in year t
	lopnrs_in_mfr_analysis
	merge_tax_data
	build_tiles
end


program lopnrs_in_mfr_analysis	
    use lopnr bfoddat birth_flag using "MYPATH\MYPATH.dta", clear
	gen bfoddat_yr = floor(bfoddat/100)
	keep if birth_flag == 1 | birth_flag == 4 // keep live births
	rename bfoddat_yr year 
	collapse (firstnm) birth_flag, by(lopnr year)
	drop birth_flag
	keep if year > 2010
	di "Right before save mfr_lopnr_yr"
	save "${TEMP}\derived\build_income_tiles\mfr_lopnr_yr.dta", replace
	di "Saved mfr_lopnr_yr first"
	
	use $DATA\master_dataset_clean, clear
	drop if undersokningsdatum_yr < 2011 
	drop if undersokningsdatum_yr > 2019
	collapse (firstnm) pregnancy, by(lopnr year) 
	drop pregnancy
	
	merge 1:1 lopnr year using $TEMP\derived\build_income_tiles\mfr_lopnr_yr.dta, ///
	  assert(1 2 3) keep(1 2 3) gen(lopnr_yr_source)
	label def lop_flag 1 "analysis" 2 "mfr" 3 "both"
	label val lopnr_yr_source lop_flag

	rm $TEMP\derived\build_income_tiles\mfr_lopnr_yr.dta
	di "Saved mfr_lopnr_yr second"
end

program merge_tax_data
	merge 1:1 lopnr year using "MYPATH\MYPATH.dta", ///
	  assert(1 2 3) keep(1 2 3) keepusing(hh_AGI_inc) gen(lisa_merge)
	replace hh_AGI_inc = hh_AGI_inc * 100
	xtset lopnr year
	gen income_t1 = L.hh_AGI_inc 
	gen income_t2 = L2.hh_AGI_inc
	gen hh_inc_smooth = max(income_t1, income_t2)
	
end

program build_tiles
	drop if lisa_merge == 2
	drop lisa_merge 
	tab year if mi(hh_inc_smooth)
	gen inc_quartile = .
	gen inc_rank = .
	forval i = 2011/2020 {
		xtile xq_1 = income_t1 if year == `i', nq(4) 
		xtile xq_2 = income_t2 if year == `i', nq(4) 
		replace inc_quartile = max(xq_1, xq_2) if year == `i'
		drop xq_1 xq_2
		xtile xq_1 = income_t1 if year == `i', nq(100) 
		xtile xq_2 = income_t2 if year == `i', nq(100) 
		replace inc_rank = max(xq_1, xq_2) if year == `i'
		drop xq_1 xq_2
	}
	codebook inc_quartile inc_rank
	save $DATA\income_tiles.dta, replace
end


* EXECUTE
main
